iT邦幫忙

2024 iThome 鐵人賽

DAY 4
0
Python

30 天學會用 Python pandas 和 openpyxl 處理 Excel —— 成為用 Python 處理 Excel 檔案的高手系列 第 4

Python pandas 增加 DataFrame 欄位以及 apply 用法【Python 處理 Excel #4】

  • 分享至 

  • xImage
  •  

本篇文章同步發布於 Python pandas 增加 DataFrame 欄位以及 apply 用法【Python 處理 Excel #4】

前言

這篇文章介紹 Python pandas 套件如何增加 DataFrame 的欄位。


文章案例說明

文章中使用 example.xlsx 作為說明用的案例資料。example.xlsx 的內容如下:

order_id order_quantity unit_price
10000 45 1000
10001 165 1000
10002 265 1200
10003 120 1000
10004 115 1000

增加 DataFrame 欄位

DataFrame 有訂單 ID (order_id)、數量 (order_quantity) 和單價 (unit_price) 欄位。假設現在想要新增訂單金額 (order_amount) 欄位,計算方式是數量乘以單價,則在 DataFrame 中新增欄位最簡單的方式如下:

import pandas as pd
# 讀取 Excel 檔案
df = pd.read_excel('example.xlsx')
# 增加 order_amount 欄位
df['order_amount'] = df['order_quantity'] * df['unit_price']
# 顯示前五個數據
print(df.head())

解釋

  • df['order_amount'] = df['order_quantity'] * df['unit_price']:計算 order_quantityunit_price 的乘積並新增一個名為 order_amount 的欄位。

使用 apply 方法和 lambda 函數增加欄位

在 pandas 中,lambda 函數常與 apply 方法結合使用,對資料進行逐列或逐行處理。

  • lambda 函數:一種匿名函數,通常用於需要簡單功能且不需要函數名稱的函數。它的語法簡潔,只能包含一個表達式。
  • apply 方法:pandas 的 apply 方法主要用於對 DataFrame 或 Series 的每一列或每一行應用自定義函數。這個方法允許使用者靈活進行數據轉換和計算,並能有效處理批量數據。
    下方程式碼展示如何使用 applylambda 增加 order_amount 欄位:
# 使用 apply 和 lambda 增加 order_amount 欄位
df['order_amount'] = df.apply(lambda row: row['order_quantity'] * row['unit_price'], axis=1)
# 顯示前五個數據
print(df.head())

解釋

  • apply:將一個函數應用於 DataFrame 的每一列或每一行。
  • lambda row: row['order_quantity'] * row['unit_price']:定義一個匿名函數,計算每一列 order_quantityunit_price 的乘積。
  • axis=1:指定應用函數的軸向,1 表示按列 (row) 操作,0 表示按行 (column) 操作。
  • df['order_amount']:將計算結果賦值給 order_amount 欄位。

使用 apply 增加複雜的欄位

當欄位背後的計算比較複雜時,可以定義一個單獨的函數,並透過 apply 應用自定義的函數。例如計算 order_amount 時,假如 order_quantity 超過 200 則享有 9 折優惠,則可以用以下方式新增訂單 order_amount 欄位:

# 定義一個計算 order_amount 的函數
def calculate_order_amount(row):
    """
    根據不同條件計算訂單金額
    Args:
        row (pd.Series): DataFrame 中的一列數據

    Returns:
        float: 計算後的訂單金額
    """
    base_amount = row['order_quantity'] * row['unit_price']
    # 假設數量超過 200 有特別的折扣
    if row['order_quantity'] > 200:
        return base_amount * 0.9  # 享有 9 折優惠
    return base_amount

# 使用 apply 和自定義函數增加 order_amount 欄位
df['order_amount'] = df.apply(calculate_order_amount, axis=1)
# 顯示前五個數據
print(df.head())

解釋

  • def calculate_order_amount(row):定義一個名稱為 calculate_order_amount 的函數,用於計算訂單金額。

    • row:函數參數,表示 DataFrame 中的一列數據。
    • base_amount = row['order_quantity'] * row['unit_price']:計算基礎金額,即 order_quantityunit_price 的乘積。
    • if row['order_quantity'] > 200:檢查 order_quantity 是否大於 200。
      • return base_amount * 0.9:如果 order_quantity 大於 200,返回打 9 折後的金額。
    • return base_amount:否則,返回基礎金額。
  • df.apply(calculate_order_amount, axis=1)

    • apply:將函數應用於 DataFrame 的每一列或每一行。
    • calculate_order_amount:自定義的計算函數。
    • axis=1:指定按列操作。
  • df['order_amount']:將計算結果賦值給 order_amount 欄位。


apply 方法的效能考量

雖然 apply 提供客製化操作,但在處理大型數據集時,使用 apply 可能會比直接使用向量化 (vectorization) 操作慢。因此,在性能要求較高的情況下,應該考慮使用其他內建函數加快運算速度。


總結

  • pandas 可以使用賦值方式輕鬆計算並新增 DataFarme 欄位。
  • apply 方法結合 lambda 函數可以對 DataFrame 的每一列進行自定義計算。
  • 當計算邏輯較為複雜時,可以定義一個函數處理不同的計算邏輯,再使用 apply 方法新增欄位。

本篇文章同步發布於 Python pandas 增加 DataFrame 欄位以及 apply 用法【Python 處理 Excel #4】


上一篇
Python pandas 選取與更變 DataFrame 欄位【Python 處理 Excel #3】
下一篇
Python 如何找到未來三個月的起迄日期?【Python 處理 Excel #5】
系列文
30 天學會用 Python pandas 和 openpyxl 處理 Excel —— 成為用 Python 處理 Excel 檔案的高手27
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言